'use strict';

const Controller = require('egg').Controller;

class CouponsController extends Controller {
  //券 详情
  async coupdetail() {
    const { ctx, app } = this
    const id = ctx.request.body.id
    ctx.validate({
      id: {
        type: 'int',
        required: true,
        desc: '券id'
      }
    })
    let list = await app.model.Coupons.findOne({
      where: {
        id
      },
      include: [
        {
          model: app.model.Shop,
          attributes: ['title', 'logo']
        }
      ]
    })
    ctx.apiSuccess(list)
  }
  //领券
  async collar() {
    const { ctx, app } = this
    const wxUser = ctx.wxUser
    ctx.validate({
      coupons_id: {
        type: 'int',
        required: true,
        desc: '券id'
      }
    })
    const { coupons_id } = ctx.request.body
    let listOne, Op, newTime
    newTime = parseInt((new Date().getTime()) / 1000)
    Op = app.Sequelize.Op
    listOne = await app.model.Coupons.findOne({
      where: {
        id: coupons_id,
        surplus_number: {
          [Op.gt]: 0,
        },
        end_time: {
          [Op.gt]: newTime,
        },
        status: '1'
      }
    })
    if (!listOne) {
      ctx.throw(400, '券剩余数量为0或者券被禁用了或券已过期')
    }
    // 查询 是否是 可以多领券 已领券
    let myCouponsOne = await app.model.CouponsCollar.findAll({
      where: {
        coupons_id: listOne.id
      },
      attributes: ['id', 'status']
    })
    if (listOne.coupon_limit == 1) { //充值后可以多领取
      myCouponsOne.forEach(item => {
        if (item.status == 1) {
          ctx.throw(400, '此券在没有充值前一人只能领券一张')
        }
      });
    } else { //只能领取一张
      if (myCouponsOne.length) {
        ctx.throw(400, '此券只能领取一张')
      }
    }
    let transaction
    // console.log('code', ctx.getCode(16))
    try {
      // 开启 事务
      transaction = await app.model.transaction();
      // 券 表操作
      await listOne.update({
        surplus_number: listOne.surplus_number - 1,
      }, { transaction })
      // 我的券表 操作
      await app.model.CouponsCollar.create({
        wx_user_id: wxUser.id,
        coupons_id: listOne.id,
        source: 1,
        code: ctx.getCode(16).toString(),
        status: '1'
      }, { transaction })
      // 提交事务
      await transaction.commit();
      return ctx.apiSuccess('操作成功');
    } catch (e) {
      // 事务回滚
      await transaction.rollback();
      return ctx.apiFail('操作失败');
    }
  }
  //  我的券列表
  async list() {
    const { ctx, app } = this
    const wxUser = ctx.wxUser
    let { status } = ctx.query
    //更改券过期状态
    if (status == 1 || status == 2) {
      let time = new Date().getTime()
      let alist = await app.model.CouponsCollar.findAll({
        where: {
          wx_user_id: wxUser.id,
          status,
        },
        attributes: ['id', 'pay_time', 'fixed_end_time', 'status'],
        include: [
          {
            model: app.model.Coupons,
            attributes: ['statr_time', 'end_time', 'fixed_days', 'fixed_statr_time', 'fixed_end_time']
          }
        ]
      })
      let aa = []
      console.log('list', alist)
      alist.forEach(item => {
        let etime
        if (item.coupon.fixed_days == 0) {
          etime = new Date(item.coupon.fixed_end_time).getTime()
        } else {
          if (status == 1) {
            etime = new Date(item.coupon.end_time).getTime()
          } else {
            etime = new Date(item.fixed_end_time).getTime()
          }
        }
        if (etime < time) {
          aa.push(item.id)
        }
      })
      await app.model.CouponsCollar.update({
        status: '4'
      }, {
        where: {
          id: aa
        }
      })
      // console.log('aaaaaaaaaaaaaa', aa)
      // ctx.apiSuccess(alist)
    }
    // return
    // ctx.apiSuccess(wxUser)
    let Op = app.Sequelize.Op
    if (status == '' || status == undefined || status == -1) {
      status = {
        [Op.gt]: 0,
      }
    }
    let list = await app.model.CouponsCollar.findAndCountAll({
      where: {
        wx_user_id: wxUser.id,
        status,
      },
      include: [
        {
          model: app.model.Coupons,
          include: [
            {
              model: app.model.Shop,
              attributes: ['id', 'title']
            }
          ]
        }
      ]
    })
    ctx.apiSuccess(list)
  }
  // 核销 二维码
  async qrcode() {
    const { ctx, app } = this
    const uid = ctx.wxUser.id
    ctx.validate({
      id: {
        type: 'int',
        required: true,
        desc: '领券表id'
      }
    })
    const { id } = ctx.query

    let listOne = await app.model.CouponsCollar.findOne({
      where: {
        wx_user_id: uid,
        id,
        status: '2'
      },
      attributes: ['id', 'wx_user_id', 'coupons_id', 'fixed_end_time']
    })
    // 验证券是否存在
    if (!listOne) {
      ctx.throw(400, '券不存在')
    }
    // 验证券是否过期
    let newTime = new Date().getTime()
    if (listOne.fixed_end_time < newTime) {
      ctx.throw(400, '券已过核销时间')
    }
    //数据
    listOne = {
      id: listOne.id,
      wx_user_id: listOne.wx_user_id,
      coupons_id: listOne.coupons_id,
      type: 'hexiao'
    }
    // ctx.apiSuccess(listOne)
    // return
    // 生成二维码
    ctx.qrcode(listOne)
  }

  // 代理 买券
  async collarcoup() {
    const { ctx, app } = this
    const wxUser = ctx.wxUser
    ctx.validate({
      coupons_id: {
        type: 'int',
        required: true,
        desc: '券id'
      },
      agent_num: {
        type: 'int',
        required: true,
        desc: '代理购买数量'
      }
    })
    const { coupons_id, agent_num } = ctx.request.body
    let newTime = new Date().getTime()
    let Op = app.Sequelize.Op
    let listOne = await app.model.Coupons.findOne({
      where: {
        id: coupons_id,
        surplus_number: {
          [Op.gte]: agent_num,
        },
        end_time: {
          [Op.gt]: newTime,
        },
        agent_purchase: '1',
        status: '1'
      }
    })
    if (!listOne) {
      ctx.throw(400, '券数量不足或者券被禁用了或券已过期或不能代理买券')
    }
    // 假设支付成功**********************
    let transaction
    try {
      // 开启 事务
      transaction = await app.model.transaction();
      // 券 表操作
      await listOne.update({
        surplus_number: listOne.surplus_number - agent_num,
      }, { transaction })
      // 我的券表 操作
      await app.model.CouponsAgent.create({
        wx_user_id: wxUser.id,
        coupons_id: listOne.id,
        agent_num
      }, { transaction })
      // 订单 表
      await app.model.Consume.create({
        wx_user_id: wxUser.id,
        detaill: `代理购买券,${listOne.title},单价${listOne.agent_price},数量${agent_num}`,
        code: ctx.getCode(16),
        money: '-' + agent_num * listOne.agent_price
      }, { transaction })
      // 提交事务
      await transaction.commit();
      return ctx.apiSuccess('操作成功');
    } catch (e) {
      // 事务回滚
      await transaction.rollback();
      return ctx.apiFail('操作失败');
    }
  }

  // 我的券 充值
  async recharge() {
    const { ctx, app } = this
    const wxUser = ctx.wxUser
    ctx.validate({
      id: {
        type: 'int',
        required: true,
        desc: '我的券id'
      }
    })
    const { id } = ctx.request.body
    let listOne = await app.model.CouponsCollar.findOne({
      where: {
        wx_user_id: wxUser.id,
        id,
        status: '1'
      },
      include: [
        {
          model: app.model.Coupons,
          // as: 'coupons',
          attributes: ['id', 'title', 'pay_price', 'end_time', 'fixed_days', 'fixed_statr_time', 'fixed_end_time', 'service_charge']
        }
      ]
    })
    // 验证券是否存在
    if (!listOne) {
      ctx.throw(400, '券不存在')
    }
    // ctx.apiSuccess(listOne)
    // return
    // 验证券是否过期
    let newTime = new Date().getTime()
    if (new Date(listOne.coupon.end_time).getTime() < newTime) {
      ctx.throw(400, '券已过充值时间段')
    }
    let fixed_time
    if (listOne.coupon.fixed_days == 0) {
      fixed_time = listOne.coupon.fixed_end_time
    } else {
      let aa = newTime + fixed_days * 3600 * 24
      fixed_time = new Date(aa)
    }
    // console.log(fixed_time)
    // return
    // 假设支付成功
    let transaction
    try {
      // 开启 事务
      transaction = await app.model.transaction();
      let fixed_time
      if (listOne.coupon.fixed_days == 0) {
        fixed_time = listOne.coupon.fixed_end_time
      } else {
        let aa = newTime + fixed_days * 3600 * 24
        fixed_time = new Date(aa)
      }
      // console.log('fixed_time', fixed_time)
      //系统 交易表
      await app.model.XiProfit.create({
        content: `${wxUser.nickname}充值优惠券${listOne.coupon.title},充值金额${listOne.coupon.pay_price}`,
        code: listOne.code,
        price: `${listOne.coupon.pay_price}`
      }, { transaction })
      //  我的券表 操作
      await listOne.update({
        status: '2',
        pay_time: new Date(),
        fixed_end_time: fixed_time,
      }, { transaction })
      // 订单 表
      await app.model.Consume.create({
        wx_user_id: wxUser.id,
        detaill: `充值优惠券,${listOne.coupon.title},单价${listOne.coupon.pay_price},数量1`,
        code: listOne.code,
        money: '-' + listOne.coupon.pay_price
      }, { transaction })
      // 提交事务
      await transaction.commit();
      return ctx.apiSuccess('操作成功');
    } catch (e) {
      // 事务回滚
      await transaction.rollback();
      return ctx.apiFail('操作失败');
    }
  }
  //赠送 二维码
  async zscode() {
    const { ctx, app } = this
    const uid = ctx.wxUser.id
    ctx.validate({
      id: {
        type: 'int',
        required: true,
        desc: '我是券id'
      }
    })
    const { id } = ctx.query
    let list = await app.model.CouponsCollar.findOne({
      where: {
        id,
        wx_user_id: uid,
        status: '2'
      }
    })
    if (!list) {
      ctx.throw(400, '我的券不存在')
    }
    let alist = {
      id,
      type: 'collar'
    }
    ctx.qrcode(alist)
  }
  //申请退款
  async refund() {
    const { ctx, app } = this;
    const uid = ctx.wxUser.id;
    const nickname = ctx.wxUser.nickname;
    const { id } = ctx.request.body;
    let collarList = await app.model.CouponsCollar.findOne({
      where: {
        id,
        wx_user_id: uid,
        source: ['1', '2'],
        status: '2'
      },
      include: [
        {
          model: app.model.Coupons,
          attributes: ['title', 'pay_price', 'refund_fee1', 'refund_fee2', 'refund_fee3']
        }
      ]
    })
    if (!collarList) {
      ctx.throw(400, '卡券不存在或卡券不是你充值的')
    }
    let time = new Date().getTime() //当前时间戳
    let type = {
      name: '',
      value: 0
    }
    let paytime = new Date(collarList.pay_time).getTime()
    let fixedendtime = new Date(collarList.fixed_end_time).getTime()
    if (time - paytime < 24 * 3600000) {
      type = {
        name: '24小时内',
        value: collarList.coupon.refund_fee1
      }
    } else if (time - paytime > 24 * 3600000 && time < fixedendtime) {
      type = {
        name: '已过24小时但券还在使用期',
        value: collarList.coupon.refund_fee2
      }
    } else {
      type = {
        name: '券已过使用期',
        value: collarList.coupon.refund_fee3
      }
    }
    let refund_amount, service_charge
    service_charge = collarList.coupon.pay_price * (type.value/100) //手续费
    refund_amount = collarList.coupon.pay_price - service_charge//退款金额
    let transaction
    try {
      // 开启 事务
      transaction = await app.model.transaction();
      // 修改我的券表状态
      await collarList.update({ status: '6' },  { transaction })
      //添加退款记录
      await app.model.Refund.create({
        collar_id: collarList.id,
        user_id: uid,
        type: type.name,
        recharge_amount: collarList.coupon.pay_price,
        refund_amount,
        service_charge
      }, { transaction })
      //系统总金额表
      await app.model.XiProfit.create({
        content: `${nickname}退优惠券${collarList.coupon.title},退款金额${refund_amount}`,
        code: collarList.code,
        price: `-${refund_amount}`
      }, { transaction })
      //我的消费记录 删除
      await app.model.Consume.destroy({
        where: {
          code: collarList.code
        }
      }, { transaction })
      // 提交事务
      await transaction.commit();
      return ctx.apiSuccess('操作成功');
    } catch (e) {
      // 事务回滚
      await transaction.rollback();
      return ctx.apiFail('操作失败');
    }
  }
}

module.exports = CouponsController;
